package jdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * JDBC API详解:Statement:
 *          int executeUpdate(String sql) throws SQLException; 执行DML、DDL语句
 *          ResultSetDemo executeQuery(String sql) throws SQLException; 执行DQL语句 返回一个结果集
 *
 */
public class StatementDemo {

    /**
     * 执行对于的DML语句
     *
     * @throws Exception
     */
    @Test
    public void test1() throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_database?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true",
                "root", "1234");

        Statement stat = conn.createStatement();

        String sql1 = "update account set money = money - 1000 where id = 1 ";
        // 如果受影响的行数大于0则执行成功,否则执行失败
        int i = stat.executeUpdate(sql1); // 执行完DML语句,受影响的行数
        if (i > 0){
            System.out.println("修改成功~");
        } else {
            System.out.println("修改失败~");
        }

        conn.close();
        stat.close();
    }

    /**
     * 执行对于的DDL语句
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_database?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true",
                "root", "1234");

        Statement stat = conn.createStatement();

        String sql1 = "drop database db1";
        // DDL语句执行后,执行成功也可能返回0,所以此时可以根据是否有异常来判断是否执行成功
        int i = stat.executeUpdate(sql1);

        conn.close();
        stat.close();
    }
}
